package com.zhengjiang.bigdecimal;

import java.math.BigDecimal;
import java.util.Random;

/**
 * @author zhengjiang
 * @version 1.0.0
 * @description double浮点数运算工具
 * @date 2021/5/31
 **/
public class Arith {

    //默认除法运算精度
    private static final int DEF_DIV_SCALE = 10;
    private Arith(){
    }

    public static double add(double d1 ,double d2){
        BigDecimal b1 = BigDecimal.valueOf(d1);
        BigDecimal b2 = BigDecimal.valueOf(d2);
        return b1.add(b2).doubleValue();
    }

    public static double sub(double d1 ,double d2){
        BigDecimal b1 = BigDecimal.valueOf(d1);
        BigDecimal b2 = BigDecimal.valueOf(d2);
        return b1.subtract(b2).doubleValue();
    }

    public static double mul(double d1,double d2){
        BigDecimal b1 = BigDecimal.valueOf(d1);
        BigDecimal b2 = BigDecimal.valueOf(d2);
        return b1.multiply(b2).doubleValue();
    }

    //除不尽的运算精确到小数点后10位
    public static double div(double d1,double d2){
        BigDecimal b1 = BigDecimal.valueOf(d1);
        BigDecimal b2 = BigDecimal.valueOf(d2);
        return b1.divide(b2,DEF_DIV_SCALE,BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 设置 double类型的精度,按四舍五入进位
     * @param d 数值
     * @param scale 精度
     * @return
     */
    public static double getDouble(double d,int scale){
        return new BigDecimal(d).setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static void main(String[] args) {
        System.out.println("0.5 + 0.1 = " + add(0.5,0.1));
        System.out.println("0.5 - 0.1 = " + sub(0.5,0.1));
        System.out.println("0.5 * 0.1 = " + mul(0.5,0.1));
        System.out.println("0.5 / 0.3 = " + div(0.5,0.3));
        System.out.println(getDouble(new Random().nextInt(20),0));
        System.out.println(Double.valueOf(new Random().nextInt(20)));
    }
}
